package com.forlove.app.qselect.login.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.forlove.app.ForloveConfig;
import com.forlove.app.R;
import com.forlove.app.common.base.litehybird.LHConstant;
import com.forlove.app.common.base.litehybird.LHPreferences;
import com.forlove.app.common.base.litehybird.WebViewFragment;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.LocationUtils;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.NetworkUtils;
import com.forlove.app.common.utils.PermissionsChecker;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.widget.CircleImageView;
import com.forlove.app.manager.DataManager;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.qselect.login.entity.GpsEntity;
import com.forlove.app.qselect.login.entity.LimitEntity;
import com.forlove.app.qselect.login.presenter.PermissionCheckerPresenter;
import com.forlove.app.qselect.login.ui.webstatus.LoadingErrorView;
import com.forlove.app.qselect.login.ui.webstatus.LoadingView;
import com.forlove.app.qselect.login.view.PermissionCheckerView;
import com.forlove.app.qselect.login.widget.SetGpsDialog;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

import static com.forlove.app.qselect.login.ui.ChoiceNewAgeActivity.REQUEST_GPS;

/**
 * gps和通讯录权限授予页
 * Created by yjl on 2017/11/6.
 */

@RuntimePermissions
public class PermissionCheckerActivity extends BaseActivity<PermissionCheckerPresenter> implements View.OnClickListener, PermissionCheckerView {

    @BindView(R.id.view_author_gps)
    RelativeLayout view_author_gps;

    @BindView(R.id.text_author_gps)
    TextView text_author_gps;

    @BindView(R.id.image_gps_selected)
    CircleImageView image_gps_selected;

    @BindView(R.id.text_next_step)
    TextView text_next_step;

    @BindView(R.id.load_gps)
    ContentLoadingProgressBar load_gps;

    private WebViewFragment webviewFragment;
    private HandlerThread locationThread;
    private Handler getLocationHandler;
    private Handler locationHandler;
    private AMapLocationClientOption locationOption = null;
    private AMapLocationClient locationClient = null;
    private SetGpsDialog setGpsDialog;
    private boolean getGps = false;//是否获取到了gps
    private long getGpsTime = 0;

    @Override
    public int getLayoutId() {
        return R.layout.activity_permission_author;
    }


    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void needLocationPermission() {
        //获取到权限
        hasGpsPermission();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionCheckerActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void refuseLocationPermission() {
        LogUtil.e("yjl", "拒绝了gps授权");

    }

    @OnNeverAskAgain({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void neverAskPermission() {
        //不再请求，跳转至设置页
        Toast.makeText(this, getString(R.string.str_tip_authorize_gps), Toast.LENGTH_LONG).show();
        view_author_gps.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PermissionsChecker.getLocationPermission(PermissionCheckerActivity.this)) {
                    if (NetworkUtils.instance(PermissionCheckerActivity.this).isNetworkAvailable()) {
                        PermissionCheckerActivityPermissionsDispatcher
                                .needLocationPermissionWithPermissionCheck(PermissionCheckerActivity.this);
                    } else {
                        Toast.makeText(PermissionCheckerActivity.this, "请检查网络!", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    PermissionsChecker.gotoPermissionSettings(PermissionCheckerActivity.this);
                }
            }
        });

    }

    @Override
    public void initView() {
        if (presenter == null) {
            presenter = new PermissionCheckerPresenter(this);
        }
        view_author_gps.setOnClickListener(this);
        webviewFragment = (WebViewFragment) getFragmentManager().findFragmentById(R.id.fg_webview);
        text_next_step.setVisibility(View.INVISIBLE);

        text_next_step.setOnClickListener(this);
//        String mUrl = "https://www.yijiedai.com";
        String mUrl = getIntent().getStringExtra("loadUrl");
        initWeb(mUrl);
        if (PermissionsChecker.getLocationPermission(this)) {
            hasGpsPermission();
//            view_author_gps.setClickable(false);
        } else {
            hideSelectedGpsPermission();
        }

        if (locationHandler == null) {
            locationHandler = new Handler(getMainLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    //处理gps成功请求
                    if (msg.what == 20008) {
                        synchronized (this) {
                            //获取gps成功
                            GpsEntity entity = (GpsEntity) msg.obj;
                            if (entity != null) {
                                LogUtil.e("yjl", "gps lng:" + entity.lng + "  lat:" + entity.lat);
                                load_gps.setVisibility(View.VISIBLE);
                                getGps = true;
                                getLocationSuccess(entity);
                                showSelectedGpsPermission();
                                if (System.currentTimeMillis() - getGpsTime < 1000) {
                                    getGpsTime = System.currentTimeMillis();
                                    return;
                                }
                                requestLimit(entity);
                            }
                        }
                    } else if (msg.what == 20009) {
                        //开始加载gps
                        load_gps.setVisibility(View.VISIBLE);
                    } else if (msg.what == 12) {
                        // 转到手机设置界面，用户设置GPS
//                        Toast.makeText(PermissionCheckerActivity.this,
//                                "获取位置服务失败，请在设置中打开位置服务：" + msg.what, Toast.LENGTH_SHORT).show();
                        Toast.makeText(PermissionCheckerActivity.this,
                                "获取位置服务失败，请在设置中打开位置服务", Toast.LENGTH_SHORT).show();
                        load_gps.setVisibility(View.INVISIBLE);
                        showTipDialog();
                    } else {
//                        Toast.makeText(PermissionCheckerActivity.this,
//                                "暂时无法获取位置信息：" + msg.what, Toast.LENGTH_SHORT).show();
                        Toast.makeText(PermissionCheckerActivity.this, "暂时无法获取位置信息", Toast.LENGTH_SHORT).show();
                        load_gps.setVisibility(View.INVISIBLE);
                    }
                }
            };
        }
    }

    private void getLocationSuccess(GpsEntity entity) {
        Intent intent = getIntent();
        Bundle bundle = new Bundle();
        bundle.putSerializable("gps", entity);
        intent.putExtras(bundle);
        setResult(ChoiceNewAgeActivity.RESULT_GPS_SUCCESS, intent);
    }

    private void requestLimit(GpsEntity entity) {
        Map param = new HashMap();
        if (entity != null) {
            param.put("lat", entity.lat);
            param.put("lng", entity.lng);
        }
        presenter.loadLimitData(param);
    }

    private void showTipDialog() {
        if (setGpsDialog == null) {
            setGpsDialog = new SetGpsDialog(this);
            setGpsDialog.setAgreeListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, REQUEST_GPS); // 设置完成后返回到原来的界面
                }
            });
        }
        setGpsDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.e("yjl", "requestCode:" + requestCode);
        if (requestCode == REQUEST_GPS) {
            if (setGpsDialog != null) {
                setGpsDialog.dismiss();
            }
            getGPSLocation();
        }
    }

    private void hasGpsPermission() {
        load_gps.setVisibility(View.VISIBLE);
        getGPSLocation();
        view_author_gps.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!getGps) {
                    Toast.makeText(PermissionCheckerActivity.this, "正在获取位置信息,请稍后!", Toast.LENGTH_SHORT).show();
                }
                load_gps.setVisibility(View.VISIBLE);
                getGPSLocation();
            }
        });
    }

    private void initWeb(String mUrl) {
        // 设置参数
        LHPreferences preferences = new LHPreferences();
        preferences.setLoadingView(new LoadingView(this));
        preferences.setLoadingErrorView(new LoadingErrorView(this));
        preferences.set("AppendUserAgent", "loadWebPermission");
        if (ForloveConfig.IS_DEBUG) {
            preferences.set(LHConstant.IS_DEBUG_MODE, true);
        }
        webviewFragment.setArguments(preferences, null);
        // 启动加载
        if (StringUtils.isNotEmpty(mUrl)) {
            webviewFragment.loadUrl(mUrl);
        }
    }


    private void showSelectedGpsPermission() {
        if (load_gps.isShown()) {
            load_gps.setVisibility(View.INVISIBLE);
        }
        view_author_gps.setBackground(getResources().getDrawable(R.drawable.bg_author_permission));
        image_gps_selected.setVisibility(View.VISIBLE);
        text_author_gps.setTextColor(getResources().getColor(R.color.white));
    }

    private void hideSelectedGpsPermission() {
        view_author_gps.setBackground(getResources().getDrawable(R.drawable.bg_unauthor_permission));
        image_gps_selected.setVisibility(View.INVISIBLE);
        text_author_gps.setTextColor(getResources().getColor(R.color.common_green));
    }

    /**
     * 开始获取gps
     */
    private synchronized void getGPSLocation() {
        if (locationThread == null) {
            locationThread = new HandlerThread("getLocation");
            locationThread.start();
        }
        if (getLocationHandler == null) {
            getLocationHandler = new Handler(locationThread.getLooper());
        }
        if (System.currentTimeMillis() - getGpsTime < 1000) {
            getGpsTime = System.currentTimeMillis();
            return;
        } else {
            getLocationHandler.post(runnable);
        }

    }


    //请求gps操作
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //初始化client
            if (locationClient == null) {
                locationOption = LocationUtils.getDefaultOption();
                locationClient = new AMapLocationClient(getApplicationContext());
                //设置定位参数
                locationClient.setLocationOption(locationOption);
            }
            // 设置定位监听
            locationClient.setLocationListener(new AMapLocationListener() {
                @Override
                public void onLocationChanged(AMapLocation location) {
                    synchronized (this) {
                        if (location != null) {
                            if (location.getErrorCode() == 0) {
                                LogUtil.e("yjl", "location code:" + location.getErrorCode()
                                        + "   address:" + location.getAddress());
                                //获取成功
                                GpsEntity gpsEntity = new GpsEntity();
                                gpsEntity.lng = String.valueOf(location.getLongitude());
                                gpsEntity.lat = String.valueOf(location.getLatitude());
                                DataManager.saveLocaition(PermissionCheckerActivity.this, gpsEntity);
                                if (locationHandler != null) {
                                    Message message = new Message();
                                    message.what = 20008;
                                    message.obj = gpsEntity;
                                    locationHandler.sendMessage(message);
                                }
                            } else {
                                //获取gps失败
                                if (locationHandler != null) {
                                    locationHandler.sendEmptyMessage(location.getErrorCode());
                                }
                                LogUtil.e("yjl", "location code:" + location.getErrorCode()
                                        + "   getErrorInfo:" + location.getErrorInfo());
                            }
                        }
                    }

                }
            });


            locationClient.startLocation();
            if (locationHandler != null) {
                locationHandler.sendEmptyMessage(20009);
            }
        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.view_author_gps:
                if (NetworkUtils.instance(PermissionCheckerActivity.this).isNetworkAvailable()
                        && !PermissionsChecker.getLocationPermission(this)) {
                    PermissionCheckerActivityPermissionsDispatcher.needLocationPermissionWithPermissionCheck(this);
                } else {
                    Toast.makeText(PermissionCheckerActivity.this, "请检查网络!", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.text_next_step:
                canRegister();
                break;
        }
    }

    private void registerUnavailable() {
        //不能注册
        text_next_step.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(PermissionCheckerActivity.this, LimitAreaActivity.class));
            }
        });

    }

    private void canRegister() {
        text_next_step.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetworkUtils.instance(PermissionCheckerActivity.this).isNetworkAvailable()) {
                    startActivity(new Intent(PermissionCheckerActivity.this, RegisterPhoneActivity.class));
                    finish();
                } else {
                    Toast.makeText(PermissionCheckerActivity.this, "请检查网络!", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, String msg) {
        super.showErrorData(resultCode, msg);
        load_gps.setVisibility(View.INVISIBLE);
    }

    public void updateLimitView(LimitEntity limitEntity) {
        load_gps.setVisibility(View.INVISIBLE);
        if (limitEntity != null) {
            if (!limitEntity.canreg) {
                Toast.makeText(PermissionCheckerActivity.this, "该地区暂时无法注册!", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(PermissionCheckerActivity.this, LimitAreaActivity.class));
                registerUnavailable();
            } else {
                text_next_step.setVisibility(View.VISIBLE);
                canRegister();
            }
        }
    }


}
